package com.tsxy.controller.administrator;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.tsxy.common.APIResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tsxy.controller.dto.BookDto;
import com.tsxy.controller.dto.BookFileRela;
import com.tsxy.entity.BookPictureRelation;
import com.tsxy.entity.Files;
import com.tsxy.entity.User;
import com.tsxy.mapper.BookMapper;
import com.tsxy.mapper.BookPictureRelationMapper;
import com.tsxy.mapper.FileMapper;
import com.tsxy.service.FilesService;
import com.tsxy.service.IBookPictureRelationService;
import org.apache.poi.util.StringUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.tsxy.service.IBookService;
import com.tsxy.entity.Book;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 飞
 * @since 2022-03-05
 */
@RestController
@RequestMapping("/book")
public class BookController {

    @Resource
    private IBookService bookService;
    @Resource
    private BookMapper bookMapper;

    
    @Resource
    private FilesService filesService;

    @Resource
    private IBookPictureRelationService bookPictureRelationService;

    @Resource
    private BookPictureRelationMapper bookPictureRelationMapper;


    //新增或者修改
    @PostMapping
    public APIResult save(@RequestBody Book book){
        return APIResult.success(bookService.saveOrUpdate(book));
    }
    //新增或者修改
    @PostMapping("/insert")
    @Transactional
    public APIResult insertWithFile(@RequestBody Book book){
        // 先添加book记录
        bookService.saveOrUpdate(book);
        //根据file名字查询file的id
        List<Files> files = book.getFilesList();

        List<Integer> ids = files.stream().map(Files::getId).collect(Collectors.toList());
        Map<Integer,String> idName = files.stream().collect( Collectors.toMap(Files::getId, Files::getLocalName) );
        //添加book和file的关系
        if (ids != null && ids.size() > 0){
            int i = bookPictureRelationService.insertRelationBatch(book.getId(), ids,idName);
        }else {
            QueryWrapper<BookPictureRelation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("book_id", book.getId());
            bookPictureRelationMapper.delete(queryWrapper);
        }

        return APIResult.success(1);
    }
    //根据id删除
    @DeleteMapping("/{id}")
    public APIResult delete(@PathVariable Integer id) {
        return APIResult.success(bookService.removeById(id));
    }
    //批量删除
    @PostMapping("/del/batch")
        public APIResult deleteBath(@RequestBody List<Integer> ids){
        return APIResult.success(bookService.removeAllIds(ids));
    }
    //查询所有
    @GetMapping
    public APIResult findAll() {
        return APIResult.success(bookService.list());
    }
    //根据id查询
    @GetMapping("/{id}")
        public APIResult findOne(@PathVariable Integer id) {
        return APIResult.success(bookService.getById(id));
    }
    //分页查询
    @GetMapping("/page")
    public APIResult findPage(@RequestParam Integer pageNum,
                    @RequestParam Integer pageSize,
                              @RequestParam(defaultValue = "")String name) {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        if (name != null && name.length()!=0){
            queryWrapper.like("name",name);
        }
        queryWrapper.orderByDesc("id");
        List<BookFileRela> relas = bookPictureRelationService.selectAllRelation();
        System.out.println(relas);
        return APIResult.success(bookService.page(new Page<>(pageNum,pageSize), queryWrapper));
    }

    //分页查询
    @GetMapping("/page2")
    public APIResult findPage2(@RequestParam Integer pageNum,
                              @RequestParam Integer pageSize,
                              @RequestParam(defaultValue = "")String name,
                               @RequestParam(defaultValue = "")String author) {
        if ( StrUtil.isBlank(name) ){
            name = null;
        }
        if ( StrUtil.isBlank(author) ){
            author = null;
        }
        List<BookDto> all = bookService.getAll(name,author,pageNum,pageSize);
        APIResult apiResult = new APIResult();
        apiResult.setData(all);
        Integer Total = bookService.cont();
        apiResult.setTotal(Total);
        apiResult.setStatus("200");
        return apiResult;
    }

    //导出excel
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        List<Book> books = bookService.list();
        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("name", "name");
        writer.addHeaderAlias("author", "author");
        writer.addHeaderAlias("bookSortId", "用户名");
        writer.addHeaderAlias("dscp", "dscp");
        writer.addHeaderAlias("price", "price");
        writer.addHeaderAlias("phone", "phone");
        writer.addHeaderAlias("version", "version");
        writer.addHeaderAlias("suit", "suit");
        writer.addHeaderAlias("count", "count");
        writer.addHeaderAlias("status", "status");


        writer.setOnlyAlias(true);
        writer.merge(8, "商品");

        writer.write(books, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("商品信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");

        ServletOutputStream out=response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }

}

